/**
 * 
 */
package com.gametime.setup;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.Random;

import com.gametime.model.Person;
import com.gametime.util.DBUtils;


/**
 * @author dave
 *
 */
public class NameGenerator 
{

	/**
	 * @param args
	 */
	private static NameGenerator instance=null;
	private int maxFirstNames=0;
	private int maxLastNames=0;
	
	
	private NameGenerator() throws Exception
	{
	  Connection conn = null;
	  final String sql = "call initNameGenerator(?,?);";
	  CallableStatement cs =null;
	  try
	  {
	    conn = DBUtils.getInstance().getConnection();
	    cs = conn.prepareCall(sql);
	    cs.registerOutParameter(1, java.sql.Types.INTEGER);
	    cs.registerOutParameter(2, java.sql.Types.INTEGER);
	    cs.execute();
	    maxFirstNames = cs.getInt(1);
	    maxLastNames = cs.getInt(2);
	    
	  }catch(Exception e)
	  {
	    throw e;
	  }finally
	  {
	    cs.close();
	    DBUtils.closeConnection(conn);
	  }
	}
	
	
	public static NameGenerator getInstance() 
	throws Exception
	{
		if(instance == null)
			instance =new NameGenerator();
		return instance;
	}
	
	public void generatePerson(Person p) throws Exception 
	{
		Random r = new Random();
		int randomFirstNameSequence = r.nextInt(maxFirstNames) + 1;
		int randomLastNameSequence = r.nextInt(maxLastNames) + 1;
		final String sql = "call getName(?,?,?,?);";
		Connection conn = null;
		CallableStatement cs =null;
		try
		{
		  conn = DBUtils.getInstance().getConnection();
		  cs = conn.prepareCall(sql);
	    cs.setInt(1, randomFirstNameSequence);
	    cs.setInt(2, randomLastNameSequence);
	    cs.registerOutParameter(3, java.sql.Types.VARCHAR);
	    cs.registerOutParameter(4, java.sql.Types.VARCHAR);
	    cs.execute();
	    p.setFirstName(cs.getString(3));
	    p.setLastName(cs.getString(4));
	    
		}catch(Exception e)
		{
		  throw e;
		}finally
		{
		  cs.close();
      DBUtils.closeConnection(conn); 
		}
	  
	}
	
	
	
	

}
